import { useAtom } from "jotai";
import { useEffect, useState } from "react";
import {
  userInfoAtom,
  sessionInfoAtom,
  setUserLogoutAtom,
  isSessionNearExpiryAtom,
  sessionTimeRemainingAtom,
  refreshSessionAtom
} from "../store/userStore";

/**
 * 用户信息展示组件
 * 显示当前登录用户的信息和会话信息
 */
export function UserInfo() {
  const [userInfo] = useAtom(userInfoAtom);
  const [sessionInfo] = useAtom(sessionInfoAtom);
  const [, setUserLogout] = useAtom(setUserLogoutAtom);
  const [isNearExpiry] = useAtom(isSessionNearExpiryAtom);
  const [timeRemaining] = useAtom(sessionTimeRemainingAtom);
  const [, refreshSession] = useAtom(refreshSessionAtom);

  const [collapsed, setCollapsed] = useState(false);

  // 每分钟更新一次时间显示（触发 timeRemaining 重新计算）
  useEffect(() => {
    const timer = setInterval(() => {
      // 这里不需要存储时间，只需要触发组件重新渲染
      // timeRemaining atom 会自动重新计算
    }, 60000);

    return () => clearInterval(timer);
  }, []);

  if (!userInfo || !sessionInfo) {
    return null;
  }

  // 格式化剩余时间显示
  const formatTimeRemaining = (ms: number) => {
    const hours = Math.floor(ms / (1000 * 60 * 60));
    const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
    return `${hours}时${minutes}分`;
  };

  const handleLogout = async () => {
    try {
      // 调用服务器端登出接口
      const response = await fetch("/api/sso/logout", {
        method: "POST",
        credentials: "include" // 包含cookies
      });

      const data = await response.json();
      console.log("服务器登出响应:", data);

      // 无论服务器响应如何，都清除本地状态
      setUserLogout();

      // 可以在这里添加更多登出逻辑，比如清除本地存储等
      localStorage.clear();
      sessionStorage.clear();

      console.log("用户已登出");

      // 重定向到登录页面
      window.location.href = "http://localhost:5173/";
    } catch (error) {
      console.error("登出过程中发生错误:", error);
      // 即使发生错误，也清除本地状态
      setUserLogout();
      localStorage.clear();
      sessionStorage.clear();
      window.location.href = "http://localhost:5173/";
    }
  };

  return (
    <div
      className={`fixed top-4 right-4 bg-white shadow-lg rounded-lg border transition-all duration-300 ${
        collapsed ? "w-16 h-16" : "min-w-[300px]"
      } ${isNearExpiry ? "ring-2 ring-orange-400" : ""}`}
    >
      {/* 折叠/展开按钮 */}
      <button
        onClick={() => setCollapsed(!collapsed)}
        className="absolute top-2 right-2 text-gray-400 hover:text-gray-600 text-sm"
      >
        {collapsed ? "📊" : "−"}
      </button>

      {collapsed ? (
        // 折叠状态：只显示用户名首字母和状态指示器
        <div className="flex flex-col items-center justify-center h-full">
          <div
            className={`w-8 h-8 rounded-full flex items-center justify-center text-white font-bold ${
              isNearExpiry ? "bg-orange-500" : "bg-blue-500"
            }`}
          >
            {userInfo.username.charAt(0).toUpperCase()}
          </div>
          {isNearExpiry && <div className="text-xs text-orange-600 mt-1">⚠️</div>}
        </div>
      ) : (
        // 展开状态：显示完整信息
        <div className="p-4">
          <h3 className="text-lg font-semibold mb-3 text-gray-800 pr-6">
            用户信息
            {isNearExpiry && <span className="ml-2 text-orange-500 text-sm">⚠️ 会话即将过期</span>}
          </h3>

          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-gray-600">用户名:</span>
              <span className="font-medium">{userInfo.username}</span>
            </div>

            <div className="flex justify-between">
              <span className="text-gray-600">用户ID:</span>
              <span className="font-medium">{userInfo.id}</span>
            </div>

            <div className="flex justify-between">
              <span className="text-gray-600">登录次数:</span>
              <span className="font-medium">{userInfo.loginCount}</span>
            </div>

            <div className="flex justify-between">
              <span className="text-gray-600">最后登录:</span>
              <span className="font-medium">{new Date(userInfo.lastLoginAt).toLocaleString()}</span>
            </div>

            <hr className="my-3" />

            <div className="flex justify-between">
              <span className="text-gray-600">会话ID:</span>
              <span className="font-mono text-xs">{sessionInfo.sessionId.slice(0, 8)}...</span>
            </div>

            <div className="flex justify-between">
              <span className="text-gray-600">登录时间:</span>
              <span className="font-medium">{new Date(sessionInfo.loginTime).toLocaleString()}</span>
            </div>

            <div className="flex justify-between items-center">
              <span className="text-gray-600">剩余时间:</span>
              <span className={`font-medium ${isNearExpiry ? "text-orange-600" : "text-green-600"}`}>
                {formatTimeRemaining(timeRemaining)}
              </span>
            </div>
          </div>

          {/* 操作按钮区域 */}
          <div className="flex gap-2 mt-4">
            <button
              onClick={() => refreshSession()}
              className="flex-1 px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors text-sm"
            >
              刷新会话
            </button>
            <button
              onClick={handleLogout}
              className="flex-1 px-3 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition-colors text-sm"
            >
              登出
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
